from flask import Flask, request, Response, jsonify, stream_with_context
from flask_cors import CORS
from dashscope import Application
from http import HTTPStatus

app = Flask(__name__)
CORS(app)
session_id = None

@app.route('/send_bailian_message', methods=['POST'])
def stream_response():
    print("post init.....")
    data = request.json
    prompt = data.get('message', '无效消息')
    print(f"receive message:{prompt}")
    def generate():
        global session_id
        responses = Application.call(
            api_key="sk-b8575714afad46d2a2cd5156aa11b6b5",
            app_id='8381bee7d9f74316864c0be3b2211223',  # 替换为实际的应用 ID
            prompt=prompt,
            session_id=session_id,
            stream=True,  # 流式输出
            incremental_output=True  # 增量输出
        )

        for response in responses:
            if response.status_code != HTTPStatus.OK:
                yield f"{{'status': 'error', 'request_id': '{response.request_id}', 'code': {response.status_code}, 'message': '{response.message}'}}\n\n"
            else:
                session_id = response.output.session_id
                print(f"back:{response.output.text}")
                yield f"{{'status': 'success', 'output': '{response.output.text}'}}\n\n"

    return Response(stream_with_context(generate()), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(debug=True)